<template>
  <div class="app-container">
    <!-- 身份提示 -->
    <el-tag size="small" style="margin-bottom:10px">
      当前工厂：{{ factoryId }} &nbsp; 页面：{{ project }}
    </el-tag>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车型" prop="models">
        <el-select
          v-model="queryParams.robot"
          placeholder="请选择车型"
          clearable
          @keyup.enter.native="handleQuery"
          @change="handleSelectChange" >
          <el-option
            v-for="item in midList1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工位" prop="station">
        <el-input
          v-model="queryParams.station"
          placeholder="请输入工位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数模焊点号" prop="sjNumber">
        <el-input
          v-model="queryParams.sjNumber"
          placeholder="请输入焊点号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机器人名称" prop="Robot">
        <el-select
          v-model="queryParams.robot"
          placeholder="请选择机器人型号"
          clearable
          @keyup.enter.native="handleQuery"
          @change="handleSelectChange" >
          <el-option
            v-for="item in midList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规范号" prop="gaugeNumber">
        <el-input
          v-model="queryParams.gaugeNumber"
          placeholder="请输入规范号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="材质1" prop="material1">
        <el-input
          v-model="queryParams.material1"
          placeholder="请输入材质1"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质1厚度(mm)" prop="materialThickness1">
        <el-input
          v-model="queryParams.materialThickness1"
          placeholder="请输入材质1厚度(mm)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="涂胶1" prop="gumming1">
        <el-input
          v-model="queryParams.gumming1"
          placeholder="请输入涂胶1"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质2" prop="material2">
        <el-input
          v-model="queryParams.material2"
          placeholder="请输入材质2"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质2厚度(mm)" prop="materialThickness2">
        <el-input
          v-model="queryParams.materialThickness2"
          placeholder="请输入材质2厚度(mm)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="涂胶2" prop="gumming2">
        <el-input
          v-model="queryParams.gumming2"
          placeholder="请输入涂胶2"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质3" prop="material3">
        <el-input
          v-model="queryParams.material3"
          placeholder="请输入材质3"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质3厚度(mm)" prop="materialThickness3">
        <el-input
          v-model="queryParams.materialThickness3"
          placeholder="请输入材质3厚度(mm)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="涂胶3" prop="gumming3">
        <el-input
          v-model="queryParams.gumming3"
          placeholder="请输入涂胶3"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质4" prop="material4">
        <el-input
          v-model="queryParams.material4"
          placeholder="请输入材质4"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质4厚度(mm)" prop="materialThickness4">
        <el-input
          v-model="queryParams.materialThickness4"
          placeholder="请输入材质4厚度(mm)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClear"
        >清空数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >焊接/机器人</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport1"
        >模板表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport2"
        >工艺验证表</el-button>
      </el-col>

      <el-col :span="1.5">
      <el-button size="mini" icon="el-icon-s-operation" @click="openColDlg">列设置</el-button>
      <!-- 弹窗 / drawer 都可以 -->
      <el-dialog title="显示列设置" :visible.sync="showColDlg" width="400px">
        <!-- 全选控制 -->
        <div style="margin-bottom:10px;">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
        </div>
        <el-checkbox-group v-model="checkedCols" style="display: flex; flex-direction: column;" @change="handleCheckedColsChange">
          <el-checkbox
            v-for="(label, key) in colLabels"
            :key="key"
            :label="key"
          >{{ label }}</el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
        <el-button @click="showColDlg = false">取 消</el-button>
        <el-button type="primary" @click="saveColSet">确 定</el-button>
        </span>
      </el-dialog>
      </el-col>

      <el-col :span="1.5">
        <el-tag size="mini" type="primary">当前版本:</el-tag>
        <el-select v-model="NewVersion" :placeholder="'V'+NewVersion" size="mini" style="width:80px;margin-right:2px;">
          <el-option
            v-for="item in midList2"
            :key="item.value"
            :label="`V${item.label}`"
            :value="item.value"
         ></el-option>
        </el-select>
        <el-button type="primary" size="mini" @click="doMatchFilter">确定</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tag size="mini" type="primary">版本对比:</el-tag>
        <el-select v-model="Version1" :placeholder="'V'+Version1" size="mini" style="width:80px;margin-right:2px;">
          <el-option
            v-for="item in midList2"
            :key="item.value"
            :label="`V${item.label}`"
            :value="item.value"
          ></el-option>
        </el-select>
        <span style="margin-right: 1px;">VS</span>
        <el-select v-model="Version2" :placeholder="'V'+Version2" size="mini" style="width:80px;margin-right:2px;">
          <el-option
            v-for="item in midList2"
            :key="item.value"
            :label="`V${item.label}`"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button type="primary" size="mini" @click="VersionComparison">确定</el-button>
        </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="weldList"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%;"
      :show-overflow-tooltip="true"
      empty-text="暂无数据"
    >
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="序号" type="index" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colVisible.models" label="车型" align="center" prop="models" />
      <el-table-column v-if="colVisible.station" label="工位" align="center" prop="station" />
      <el-table-column v-if="colVisible.robot" label="机器人名称" align="center" prop="robot" />
      <el-table-column v-if="colVisible.torchNumber" label="焊枪编号" align="center" prop="torchNumber" />
      <el-table-column v-if="colVisible.sjNumber" label="数模焊点号" align="center" prop="sjNumber" />
      <el-table-column v-if="colVisible.solderJoint" label="焊点号(五位焊点号)" align="center" prop="solderJoint" />
      <el-table-column v-if="colVisible.energy" label="能量" align="center" prop="energy" />
      <el-table-column v-if="colVisible.splashRate" label="飞溅率" align="center" prop="splashRate" />
      <el-table-column v-if="colVisible.gaugeNumber" label="规范号" align="center" prop="gaugeNumber" />
      <el-table-column v-if="colVisible.electrodeForm" label="电极形式" align="center" prop="electrodeForm" />
      <el-table-column v-if="colVisible.parametricForm" label="频率" align="center" prop="parametricForm" />
      <el-table-column v-if="colVisible.ratedPressure" label="额定压力" align="center" prop="ratedPressure" />
      <el-table-column v-if="colVisible.x" label="焊点坐标(X)" align="center" prop="x" />
      <el-table-column v-if="colVisible.y" label="焊点坐标(Y)" align="center" prop="y" />
      <el-table-column v-if="colVisible.z" label="焊点坐标(Z)" align="center" prop="z" />
      <el-table-column v-if="colVisible.material1" label="材质1" align="center" prop="material1" />
      <el-table-column v-if="colVisible.materialThickness1" label="材质1厚度(mm)" align="center" prop="materialThickness1" />
      <el-table-column v-if="colVisible.gumming1" label="涂胶1" align="center" prop="gumming1" />
      <el-table-column v-if="colVisible.material2" label="材质2" align="center" prop="material2" />
      <el-table-column v-if="colVisible.materialThickness2" label="材质2厚度(mm)" align="center" prop="materialThickness2" />
      <el-table-column v-if="colVisible.gumming2" label="涂胶2" align="center" prop="gumming2" />
      <el-table-column v-if="colVisible.material3" label="材质3" align="center" prop="material3" />
      <el-table-column v-if="colVisible.materialThickness3" label="材质3厚度(mm)" align="center" prop="materialThickness3" />
      <el-table-column v-if="colVisible.gumming3" label="涂胶3" align="center" prop="gumming3" />
      <el-table-column v-if="colVisible.material4" label="材质4" align="center" prop="material4" />
      <el-table-column v-if="colVisible.materialThickness4" label="材质4厚度(mm)" align="center" prop="materialThickness4" />
      <el-table-column v-if="colVisible.stress" label="压力(N)" align="center" prop="stress" />
      <el-table-column v-if="colVisible.preloadingTime" label="预压时间(ms)" align="center" prop="preloadingTime" />
      <el-table-column v-if="colVisible.pressurizationTime" label="加压时间(ms)" align="center" prop="pressurizationTime" />
      <el-table-column v-if="colVisible.preheatingMethod" label="预热方式" align="center" prop="preheatingMethod" />
      <el-table-column v-if="colVisible.preheatingTime" label="预热时间(ms)" align="center" prop="preheatingTime" />
      <el-table-column v-if="colVisible.preheatingCurrent" label="预热电流(kA)" align="center" prop="preheatingCurrent" />
      <el-table-column v-if="colVisible.coolingTime" label="冷却时间(ms)" align="center" prop="coolingTime" />
      <el-table-column v-if="colVisible.weldingMethod" label="焊接方式" align="center" prop="weldingMethod" />
      <el-table-column v-if="colVisible.increaseDecrease" label="递增递减" align="center" prop="increaseDecrease" />
      <el-table-column v-if="colVisible.incrementalTime" label="递增时间(ms)" align="center" prop="incrementalTime" />
      <el-table-column v-if="colVisible.startingCurrent" label="起始电流(KA)" align="center" prop="startingCurrent" />
      <el-table-column v-if="colVisible.weldingTime" label="焊接时间(ms)" align="center" prop="weldingTime" />
      <el-table-column v-if="colVisible.weldingCurrent" label="焊接电流(kA)" align="center" prop="weldingCurrent" />
      <el-table-column v-if="colVisible.declineTime" label="递减时间(ms)" align="center" prop="declineTime" />
      <el-table-column v-if="colVisible.terminationCurrent" label="终止电流(KA)" align="center" prop="terminationCurrent" />
      <el-table-column v-if="colVisible.coolingTime1" label="冷却时间(ms)1" align="center" prop="coolingTime1" />
      <el-table-column v-if="colVisible.pulseFrequency" label="脉冲次数" align="center" prop="pulseFrequency" />
      <el-table-column v-if="colVisible.coolingTime2" label="冷却时间(ms)2" align="center" prop="coolingTime2" />
      <el-table-column v-if="colVisible.temperingMethod" label="回火方式" align="center" prop="temperingMethod" />
      <el-table-column v-if="colVisible.temperingTime" label="回火时间(ms)" align="center" prop="temperingTime" />
      <el-table-column v-if="colVisible.temperingCurrent" label="回火电流(kA)" align="center" prop="temperingCurrent" />
      <el-table-column v-if="colVisible.holdTime" label="保持时间(ms)" align="center" prop="holdTime" />
      <el-table-column v-if="colVisible.newVersion" label="版本" align="center" prop="newVersion" />
      <el-table-column   label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePage"
    />

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form :model="upload" label-position="left" label-width="80px" size="mini">
        <!-- 1. 版本输入框 -->
        <el-form-item label="文件版本" prop="version"
          :rules="[{required:true,message:'请选择版本',trigger:'change'}]">
          <el-select  v-model="tempVersion"
                      placeholder="请选择版本"
                      size="mini"
                      style="width:260px">
            <el-option label="V1.0" value="1.0"/>
            <el-option label="V2.0" value="2.0"/>
            <el-option label="V3.0" value="3.0"/>
            <el-option label="V4.0" value="4.0"/>
          </el-select>
        </el-form-item>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?project=' + upload.project + '&version=' + upload.version.trim()"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="!tempVersion || !tempVersion.trim()" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="Export.title" :visible.sync="Export.open" width="400px" append-to-body>
      <span>是否导出全部数据</span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ExportAll">确 定</el-button>
        <el-button @click="Export.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listGeneral, getGeneral, delGeneral, addGeneral, updateGeneral} from "@/api/Factory/template_index";
import { getToken } from "@/utils/auth";
import axios from "axios";
import Exceljs from "exceljs";

export default {
  name: "WELD",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //下拉框存储的数据
      midList:[],
      midList1:[],
      //存储版本信息
      midList2:[],
      versions:[],
      tempVersion:'',
      //默认显示的版本
      NewVersion:'',
      //版本对比
      Version1:'',
      Version2:'',
      // 存储用户选择的数据项
      multipleSelection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch:false,
      // 总条数
      total: 0,
      //全部数据
      allData: [],
      // 表数据
      weldList: [],
      // 弹出层标题
      title: "",
      //导入文件的名称
      importFileName: null,
      factoryId: this.$route.params.factoryId,   // 工厂
      item_project: this.$route.params.item_project,    // 车型
      project:  this.$route.params.project,  // 车型配置
      // 用户导入参数
      upload:{
        // // 是否显示弹出层（用户导入）
        open: false,
        // // 弹出层标题（用户导入）
        title: "",
        // // 是否禁用上传
        isUploading: false,
        //版本
        version:'',
        //导入的表名
        project:this.$route.params.project,
        // // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/General/general/importData"
      },
      // 导出参数
      Export:{
        open: false,
        title: "",
      },
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        models: undefined,
        station: undefined,
        project: this.$route.params.project   // 身份字段
      },
      checkAll: false,
      isIndeterminate: false,
      showColDlg: false,         //是否打开弹窗
      checkedCols: [],          // 当前勾选
      colVisible: {
        models: true, station: true, robot: true, torchNumber: true, ratedPressure: true,
        sjNumber: true, solderJoint: true, x: true, y: true, z: true, gaugeNumber: true,
        energy: true,splashRate: true,electrodeForm: true, material1: true, materialThickness1: true,
        gumming1: true, material2: true, materialThickness2: true, gumming2: true,
        material3: true, materialThickness3: true, gumming3: true, material4: true,
        materialThickness4: true, stress: true, preloadingTime: true, pressurizationTime: true, preheatingTime: true,
        preheatingCurrent: true, coolingTime: true, incrementalTime: true, startingCurrent: true,
        weldingTime: true, weldingCurrent: true, coolingTime1: true, declineTime: true,
        terminationCurrent: true, pulseFrequency: true, coolingTime2: true, temperingTime: true,
        temperingCurrent: true, holdTime: true, parametricForm: true, newVersion: true, preheatingMethod: true,
        weldingMethod: true, increaseDecrease: true, temperingMethod: true
      },
      colLabels: {
        models: '车型', station: '工位', robot: '机器人名称', torchNumber: '焊枪编号',
        ratedPressure: '额定压力', sjNumber: '数模焊点号', solderJoint: '焊点号(五位焊点号)',
        x: '焊点坐标(X)', y: '焊点坐标(Y)', z: '焊点坐标(Z)', gaugeNumber: '规范号',energy: '能量',splashRate: '飞溅率',
        electrodeForm: '电极形式', parametricForm: '频率', material1: '材质1', materialThickness1: '材质1厚度(mm)',
        gumming1: '涂胶1', material2: '材质2', materialThickness2: '材质2厚度(mm)', gumming2: '涂胶2',
        material3: '材质3', materialThickness3: '材质3厚度(mm)', gumming3: '涂胶3', material4: '材质4',
        materialThickness4: '材质4厚度(mm)', stress: '压力(N)', preloadingTime: '预压时间(ms)', pressurizationTime: '加压时间(ms)',
        preheatingTime: '预热时间(ms)', preheatingCurrent: '预热电流(kA)', coolingTime: '冷却时间(ms)',
        incrementalTime: '递增时间(ms)', startingCurrent: '起始电流(KA)', weldingTime: '焊接时间(ms)',
        weldingCurrent: '焊接电流(kA)', coolingTime1: '冷却时间(ms)1', declineTime: '递减时间(ms)',
        terminationCurrent: '终止电流(KA)', pulseFrequency: '脉冲次数', coolingTime2: '冷却时间(ms)2',
        temperingTime: '回火时间(ms)', temperingCurrent: '回火电流(kA)', holdTime: '保持时间(ms)',
        newVersion: '版本', preheatingMethod: '预热方式', weldingMethod: '焊接方式', increaseDecrease: '递增递减',
        temperingMethod: '回火方式'
      }
    };
  },
  //页面自动执行的方法
  created() {
    if (localStorage.getItem('importFileName')) {this.importFileName = localStorage.getItem('importFileName');}

    const defaultVisible = Object.keys(this.colLabels).reduce((acc, k) => ({ ...acc, [k]: true }), {})
    this.colVisible = JSON.parse(localStorage.getItem('weldColVisible') || JSON.stringify(defaultVisible))

    this.getList();
  },

  methods: {
    //列设置，打开初始化
    openColDlg(){
      this.showColDlg = true;
      this.checkedCols = Object.keys(this.colVisible).filter(k => this.colVisible[k]);
      this.handleCheckedColsChange(this.checkedCols);
    },
    /* 全选按钮 */
    handleCheckAllChange(val) {
      this.checkedCols = val ? Object.keys(this.colLabels) : []
      this.isIndeterminate = false
    },
    /* 单个勾选变化 */
    handleCheckedColsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === Object.keys(this.colLabels).length
      this.isIndeterminate = checkedCount > 0 && checkedCount < Object.keys(this.colLabels).length
    },
    //保存列设置
    saveColSet() {
      // 把勾选数组转回对象
      const newVisible = {}
      Object.keys(this.colLabels).forEach(k => {
        newVisible[k] = this.checkedCols.includes(k)
      })
      this.colVisible = newVisible
      localStorage.setItem('weldColVisible', JSON.stringify(newVisible))
      this.showColDlg = false
    },

    //查询表格数据
    getList(){
      listGeneral(this.queryParams).then(response => {
        this.loading = true
        this.allData = response.rows;
        this.allData.forEach(element =>{
          const version = element.newVersion;
          const isDuplicate3 = this.midList2.some(item=>item.label===version && item.value===version);
          if (!isDuplicate3){
            this.midList2.push({label:element.newVersion,value:element.newVersion});
          }
        }) ;
        this.midList2.sort((a, b) => a.value - b.value);   // 升序
        this.versions = this.midList2.map(item => item.value);
        this.Version1 = this.versions[this.versions.length-1];
        this.Version2 = this.versions[this.versions.length-2];
        if (this.midList2.length === 0) {
          this.NewVersion = '无版本信息'
        }else if (localStorage.getItem(this.factoryId+this.item_project+this.project+'WELD_LastVersion')) {
          this.NewVersion=JSON.parse(localStorage.getItem(this.factoryId+this.item_project+this.project+'WELD_LastVersion'));
        }else {
          this.NewVersion = [...this.versions].sort().pop();
        }
        if (this.NewVersion)
          this.allData = this.allData.filter(r => (r.newVersion === this.NewVersion))

        this.allData.forEach(element => {
          const robot = element.robot;
          const models = element.models;
          const isDuplicate1 = this.midList.some(item=>item.label===robot && item.value===robot);
          const isDuplicate2 = this.midList1.some(item=>item.label===models && item.value===models);
          if (!isDuplicate1){
            this.midList.push({label:element.robot,value:element.robot});
          }
          if (!isDuplicate2){
            this.midList1.push({label:element.models,value:element.models});
          }
        })
        this.total = this.allData.length;
        this.slicePage();
        this.loading = false
      }).catch(err=>{
        console.log(err);
      })

    },
    //筛选数据是否匹配成功
    doMatchFilter() {
      this. doMatch();
      localStorage.setItem(this.factoryId+this.item_project+this.project+'WELD_LastVersion',this.NewVersion);
      this.$modal.msgSuccess('版本切换完成');
    },
    //机器人、车型、版本搜索下拉框和版本切换
    doMatch(){
      listGeneral(this.queryParams).then(response => {
        this.loading = true;
        this.allData = response.rows;

        if (this.NewVersion)
          this.allData = this.allData.filter(r => (r.newVersion === this.NewVersion));

        this.allData.forEach(element => {
          const robot = element.robot;
          const models = element.models;
          const isDuplicate1 = this.midList.some(item=>item.label===robot && item.value===robot);
          const isDuplicate2 = this.midList1.some(item=>item.label===models && item.value===models);
          if (!isDuplicate1){
            this.midList.push({label:element.robot,value:element.robot});
          }
          if (!isDuplicate2){
            this.midList1.push({label:element.models,value:element.models});
          }
        })
        this.total = this.allData.length;
        this.slicePage();
        this.loading = false
      }).catch(err=>{
        console.log(err);
      })
    },
    // 纯前端切片
    slicePage() {
      const { pageNum, pageSize } = this.queryParams
      const start = (pageNum - 1) * pageSize
      const end   = start + pageSize
      this.weldList = this.allData.slice(start, end)
    },
    // 翻页/每页条数切换时触发
    handlePage({ page, limit }) {
      this.queryParams.pageNum = page
      this.queryParams.pageSize = limit
      this.slicePage()
    },
    VersionComparison(){
      axios.post('/dev-api/General/general/comparison?Version1=' + this.Version1 + '&Version2=' + this.Version2,
        { project: this.project },
        { headers: {
            // 将 token 添加到请求头中，通常是 'Authorization' 头
            'Authorization': `Bearer ${getToken()}`
        }}
      ).then(res => {
        this.downloadExcel(res)
      })
    },
    async downloadExcel(res){
      try {
        const wb = new Exceljs.Workbook();
        const cols = Object.keys(this.colLabels)
        const ws1 = wb.addWorksheet(`版本${this.Version1}相比版本${this.Version2}多的`);
        const sumMany = res.data.data['多']
        ws1.columns = this.buildColumns(cols);
        sumMany.forEach(item => ws1.addRow(item))
        const ws2 = wb.addWorksheet(`版本${this.Version1}相比版本${this.Version2}少的`);
        const sumFew = res.data.data['少']
        ws2.columns = this.buildColumns(cols);
        sumFew.forEach(item => ws2.addRow(item))
        const ws3 = wb.addWorksheet(`版本${this.Version1}相比版本${this.Version2}变化的`);
        const sumBoth = res.data.data['变化'].slice().sort((a, b) => (a.sjNumber || '').localeCompare(b.sjNumber || ''));
        ws3.columns = this.buildColumns(cols);
        sumBoth.forEach(item => ws3.addRow(item))
        const buffer = await wb.xlsx.writeBuffer()
        saveAs(new Blob([buffer]), `版本对比.xlsx`)
      }catch (err) {
        console.error(err);                 // 控制台
        this.$message.error('导出失败：' + (err.message || '未知错误'));
      }
    },
    buildColumns(fields) {
      return fields.map(key => ({
        header: this.colLabels[key] || key,
        key: key,
        width: (this.colLabels[key] || key).length + 4
      }));
    },
    // 表单重置
    reset() {
      this.form = {
        ID: undefined, sjNumber: undefined,
        robot: undefined, gaugeNumber: undefined,
        position: undefined, electrodeForm: undefined,
        material1: undefined, materialThickness1: undefined,
        gumming1: undefined, material2: undefined,
        materialThickness2: undefined, gumming2: undefined,
        material3: undefined, materialThickness3: undefined,
        gumming3: undefined, material4: undefined,
        materialThickness4: undefined, stress: undefined,
        preloadingTime: undefined, preheatingTime: undefined,
        preheatingCurrent: undefined, coolingTime: undefined,
        incrementalTime: undefined, startingCurrent: undefined,
        weldingTime: undefined, weldingCurrent: undefined,
        coolingTime1: undefined, declineTime: undefined,
        terminationCurrent: undefined, pulseFrequency: undefined,
        coolingTime2: undefined, temperingTime: undefined,
        temperingCurrent: undefined, holdTime: undefined,
        parametricForm: undefined
      };
      this.resetForm("form");
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.multipleSelection =selection;
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getGeneral(ID,this.project).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateGeneral(this.form,this.project).then(()=> {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGeneral(this.form,this.project).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //删除按钮
    handleDelete(row) {
      const Ids = row.ID || this.ids;
      let displayIds=Ids;
      if (Ids.length>10){
        displayIds=Ids.slice(0,10)+"...";
      }
      this.$modal.confirm('是否确认删除编号为"' + displayIds + '"的数据项？').then(() => {
       delGeneral(Ids, this.project).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch((error) => {
          this.$modal.msgError("删除失败：" + error.message);
        });
      }).catch(() => {});
      this.midList2.length = 0;
      this.versions.length = 0;
      /* …你原来的清空逻辑… */
      localStorage.removeItem('WELD_LastVersion'); // 一起清
    },
    //清空数据
    handleClear(){
      this.$modal.confirm('是否确认清空所有数据项？').then(() =>{
        axios.delete('/dev-api/General/general/clear?project=' + this.project,
          { headers: {
            'Authorization': `Bearer ${getToken()}`
          }})
          .then(() =>{
          this.$modal.msgSuccess("清空成功！");
          this.getList();
        }).catch(error=>{
          this.$modal.msgError("清空失败：" + error.message);
        });
      }).catch(() => {});
      this.midList2.length = 0;
      this.versions.length = 0;
      /* …你原来的清空逻辑… */
      localStorage.removeItem('WELD_LastVersion'); // 一起清
    },
    // 导出焊接/机器人按钮操作
    handleExport() {
      if (this.multipleSelection.length===0){
        this.$message({
          message:"请选择导出数据",
          type: "warning",
        });
        return ;
      }
      const ids=this.multipleSelection.map(item => item.id).join(',');
      this.download('General/general/export1?project=' + this.project, {ids}, `weld_${new Date().getTime()}.xlsx`)
    },
    //导出模板表按钮操作
    handleExport1() {
      if (this.multipleSelection.length===0){
        this.Export.title = "数据导入";
        this.Export.open = true;
      }else {
        const ids = this.multipleSelection.map(item => item.id).join(',');
        this.download('General/general/export3?project=' + this.project, {ids}, `${this.importFileName}`)
      }
    },
    ExportAll(){
      this.download('General/general/exportAll?project=' + this.project,1,`${this.importFileName}`);
      this.Export.open = false;
    },
    //导出工艺验证表
    handleExport2(){
      this.download('General/general/exportAll2?project=' + this.project,1,`${this.importFileName}`);
    },
    // 导入按钮操作
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
      this.upload.version = '';
    },
    // 下载模板操作
    importTemplate() {
      this.download('General/general/importTemplate', {
      }, `XXX项目焊接参数导入模版.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      let ver =  Number(this.tempVersion );
      if (this.versions && this.versions.includes(ver)){
        while (this.versions.includes(ver)){
          ver += 0.01;
        }
      }
      this.upload.version = ver.toFixed(2);
      this.$nextTick(() => {
        this.$refs.upload.submit();
      })
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file) {
      // 保存导入文件的名称
      this.importFileName = file.name;
      // 保存到 localStorage
      localStorage.setItem('importFileName', this.importFileName);
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    //搜索框里面的下拉的数据选择
    handleSelectChange(newValue) {
      // 当选择的值变化时，这里将接收新的值作为参数
      console.log('选中的值变化为:', newValue);
      // 在这里可以执行进一步的逻辑处理
    },
  }
};
</script>
